package com.nondo.rdp.finance.service.impl.analysis;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.domain.analysis.AnalysisComment;
import com.nondo.rdp.finance.repository.analysis.AnalysisCommentRepository;
import com.nondo.rdp.finance.service.analysis.AnalysisCommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class AnalysisCommentServiceImpl implements AnalysisCommentService {
    @Autowired
    AnalysisCommentRepository analysisCommentRepository;

    @Override
    public AnalysisComment findOne(Long id) {
        return this.analysisCommentRepository.findOne(id);
    }

    @Override
    public AnalysisComment save(AnalysisComment analysisComment) {
        return this.analysisCommentRepository.save(analysisComment);
    }

    @Override
    public void update(AnalysisComment analysisComment) {
        this.analysisCommentRepository.save(analysisComment);
    }

    @Override
    public void delete(Long id) {
        this.analysisCommentRepository.deleteById(id);
    }

    @Override
    public Page<AnalysisComment> findAll(Page<AnalysisComment> page, AnalysisComment analysisComment) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<AnalysisComment> dictPage = analysisCommentRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();

            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<AnalysisComment>(dictPage);
    }
}